package com.lx.shopping.biz.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.lx.bilibili.entity.Order;

import com.lx.shopping.Init.ProjectInit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.util.Map;

/**
 *  支付宝支付，业务实现
 *
 * @author chill
 * */
@Service
@Slf4j
public class PayService {

    @Autowired
    private ProjectInit projectInit;

    /**
     * 创建支付宝支付订单（仅需金额）
     */
    public String createOrder(Order orders, String subject) {
        // 自动生成订单号
        String orderNo = generateOrderNo();

        AlipayClient alipayClient = new DefaultAlipayClient(
                projectInit.getGatewayUrl(),
                projectInit.getAppId(),
                projectInit.getMerchantPrivateKey(),
                "json",
                projectInit.getCharset(),
                projectInit.getAlipayPublicKey(),
                projectInit.getSignType());

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(projectInit.getReturnUrl() + orders.getUid());
        request.setNotifyUrl(projectInit.getNotifyUrl());

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        bizContent.put("total_amount", orders.getTotal());
//        bizContent.put("chapId", orders.getChapId());
//        bizContent.put("itemId", orders.getItemId());
//        bizContent.put("userId", orders.getUserId());
        bizContent.put("subject", subject);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());

        try {
            String form = alipayClient.pageExecute(request).getBody();
            return form;
        } catch (AlipayApiException e) {
            log.error("支付宝下单异常", e);
            throw new RuntimeException("支付宝下单异常", e);
        }
    }

    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        // 格式: 时间戳(13位) + 随机数(6位)
        return System.currentTimeMillis() + "" + (int)((Math.random() * 9 + 1) * 100000);
    }

    /**
     * 验证支付宝异步通知
     */
    public boolean verifyNotification(Map<String, String> params) {
        try {
            return AlipaySignature.rsaCheckV1(
                    params,
                    projectInit.getAlipayPublicKey(),
                    projectInit.getCharset(),
                    projectInit.getSignType());
        } catch (AlipayApiException e) {
            log.error("支付宝验签失败", e);
            return false;
        }
    }
}

